package cevent.source.cloudcenter.source.controller.admin;/**
 * Created by Cevent on 2021/6/27.
 */

import cevent.source.cloudcenter.server.dto.FileDto;
import cevent.source.cloudcenter.server.dto.ResponseDataDto;
import cevent.source.cloudcenter.server.service.FileService;
import cevent.source.cloudcenter.server.service.ModuleService;
import cevent.source.cloudcenter.server.util.UUID8Util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description element上传组件
 * @date 2021/6/27 11:14
 */
@RequestMapping("/admin")
@RestController
public class ELUpload {
    private static final Logger LOG = LoggerFactory.getLogger(ELUpload.class);
    private static final String BUSINESS_NAME = "element UI 文件上传";

    @Value("${file.targetPath}")
    private String TARGET_PATH;

    @Value("${oss.accessKeyID}")
    private String ACCESS_KEY_ID;
    @Value("${oss.accessKeySecret}")
    private String ACCESS_KEY_SECRET;
    @Value("${oss.bucket}")
    private String BUCKET;
    @Value("${oss.endpoint}")
    private String END_POINT;
    @Value("${oss.endpointfieldName}")
    private String END_POINT_FIELD_NAME;

    @Autowired
    FileService fileService;
    @Autowired
    ModuleService moduleService;

    @RequestMapping("/uploadEL")
    public ResponseDataDto uploadEL(@RequestParam MultipartFile[] file) {
        ResponseDataDto responseData = new ResponseDataDto();
        List<String> paths=new ArrayList<>();
        LOG.info("传入的files：{}",file);
        for(MultipartFile file1:file){
            LOG.info("遍历的的file1：{}", file1);
            String fileKey = UUID8Util.getShortUUID();
            String fileName = file1.getOriginalFilename();
            Long fileSize = file1.getSize();
            String fileType = file1.getContentType();
            //获取文件名
            String name = fileName.substring(0, fileName.lastIndexOf("."));
            //获取文件后缀名(类型)，全部转小写
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            LOG.info("文件名：{}，文件大小：{}，文件类型：{}，单独文件名：{}，文件后缀：{}", fileName, fileSize, fileType, name, suffix);
            //文件名配置
            Date now = new Date();
            String dateTime = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(now);
            String date = new SimpleDateFormat("yyyy-MM-dd").format(now);
            String newFileName = date + "_" + fileKey + "_" + name + "." + suffix;
            LOG.info("新文件名：{}", newFileName);
            //存储路径
            String targetPath = TARGET_PATH + newFileName;
            //IO上传
            File dest = new File(targetPath);
            try {
                file1.transferTo(dest);
            } catch (IOException e) {
                LOG.error("文件上传失败！");
                e.printStackTrace();
            }
            LOG.info("文件全路径：{}", dest.getAbsolutePath());
            String s = dest.getAbsolutePath();

            paths.add(s);

        }
        responseData.setResponseData(paths);


        return responseData;
    }

    @PostMapping("/simpleEL")
    public ResponseDataDto uploadSimpleOSS(@RequestParam MultipartFile file) throws IOException {
        //获取枚举类型，生成新的文件夹路径
        String shardKey= UUID8Util.getShortUUID();
        String fileName = file.getOriginalFilename();
        String fileKey = UUID8Util.getShortUUID();
        //获取文件后缀名(类型)，全部转小写
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        String contentType = file.getContentType();
        Long size = file.getSize();

        //文件名配置
        Date now = new Date();
        String date = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(now);
        //获取到枚举名SOURCE("","")
        String dateDir = new SimpleDateFormat("yyyy_MM_dd").format(now);
        String name = date + "_" + fileKey + "_" + fileName;
        //File.separator生成不同操作系统的/斜杠
        String path = new StringBuffer("source/").append(dateDir).append("/")
                .append(dateDir).append("_")
                .append(shardKey).append("_")
                .append(fileName)
                .toString();
        LOG.info("上传的path：{}", path);

        //保存file
        FileDto fileDto = new FileDto();
        fileDto.setName(name);
        //OSS上传
        OSS ossClient=new OSSClientBuilder().build(END_POINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        PutObjectRequest putObjectRequest=new PutObjectRequest(BUCKET,path,new ByteArrayInputStream(file.getBytes()));
        //上传字符串
        ossClient.putObject(putObjectRequest);
        //fileDto.setPath(path);
        //返回全路径
        fileDto.setUniId(shardKey);
        fileDto.setPath(path);
        fileDto.setSuffix(suffix);
        fileDto.setShardKey(shardKey);
        fileDto.setContentType(contentType);
        fileDto.setSize(Math.toIntExact(size));
        fileDto.setIsShow(0);

        fileService.save(fileDto);
        ResponseDataDto responseData = new ResponseDataDto();
        responseData.setResponseData(fileDto);
        return responseData;
    }
}
